package com.boxin.ims.modules.sys.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.sys.scheduler.AbstractScheduler;
import com.boxin.ims.modules.sys.scheduler.SchedulerInfo;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;

/**
 * @author Jakemanse
 * @date 2013-10-16
 * @function <p> 系统全局 </p>
 */
@Service
public class Application implements ApplicationContextAware {
	
	WechatDaoHelper wechatDaoHelper;
	ApplicationContext applicationContext;
	private final Logger logger = Logger.getLogger(Application.class);
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
		wechatDaoHelper = (WechatDaoHelper)applicationContext.getBean("wechatDaoHelper");
		startAllSchedulers();		
	}
	
	
	public void startAllSchedulers(){
		List<Map<String,Object>> smap = wechatDaoHelper.queryAllSchedulers(null);
		if(smap !=null && !smap.isEmpty()){
			for(Map m:smap){
				try {
					if(m.get("is_valid")!=null && (Integer)m.get("is_valid") == 1){//需要重复
						
						AbstractScheduler scheduler = (AbstractScheduler) applicationContext.getBean(m.get("name").toString());
						if(scheduler!=null){
							logger.debug("开始启动【"+m.get("name")+"】定时器...");
							Map<String,String> params = new HashMap<String,String>();
							params.put("name", m.get("name").toString());
							params.put("is_valid", "1");
							SchedulerInfo schedulerInfo = wechatDaoHelper.findSchedulerInfo(params);
							scheduler.setSchedulerInfo(schedulerInfo);
							scheduler.start();
							//scheduler.restart();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}
	}

}
